import backtrader as bt


class LivermoreStrategy(bt.Strategy):
    params = (
        ("min_percentage_change", 2),  # 最小价格变动百分比触发买入或卖出
        ("stop_loss_percentage", 3),  # 止损百分比
        ("take_profit_percentage", 5),  # 止盈百分比
    )

    def __init__(self):
        self.dataclose = self.datas[0].close
        self.order = None
        self.buy_price = None
        self.buy_size = None

    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            return

        if order.status in [order.Completed]:
            if order.isbuy():
                self.buy_price = order.executed.price
                self.buy_size = order.executed.size
                self.log(
                    f"BUY EXECUTED, Price: {order.executed.price}, Cost: {order.executed.value}, Size: {order.executed.size}"
                )
            elif order.issell():
                self.log(
                    f"SELL EXECUTED, Price: {order.executed.price}, Cost: {order.executed.value}, Size: {order.executed.size}"
                )
            self.order = None

        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log("Order Canceled/Margin/Rejected")

    def next(self):
        if not self.position:
            # 判断是否满足买入条件
            if self.dataclose[0] > self.dataclose[-1] * (
                1 + self.params.min_percentage_change / 100
            ):
                self.order = self.buy()
        else:
            # 计算止损价格和止盈价格
            stop_loss_price = self.buy_price * (
                1 - self.params.stop_loss_percentage / 100
            )
            take_profit_price = self.buy_price * (
                1 + self.params.take_profit_percentage / 100
            )

            # 判断是否达到止损或止盈条件
            if self.dataclose[0] < stop_loss_price:
                self.close()
            elif self.dataclose[0] > take_profit_price:
                self.close()

    def log(self, txt):
        dt = self.datas[0].datetime.date(0)
        print(f"{dt}, {txt}")


if __name__ == "__main__":
    cerebro = bt.Cerebro()
    data = bt.feeds.GenericCSVData(
        dataname="your_data.csv",
        dtformat=("%Y-%m-%d"),
        datetime=0,
        open=1,
        high=2,
        low=3,
        close=4,
        volume=5,
        openinterest=-1,
    )
    cerebro.adddata(data)
    cerebro.addstrategy(LivermoreStrategy)
    cerebro.broker.setcash(100000.0)
    cerebro.broker.setcommission(commission=0.001)
    print("Starting Portfolio Value: %.2f" % cerebro.broker.getvalue())
    cerebro.run()
    print("Final Portfolio Value: %.2f" % cerebro.broker.getvalue())
